package com.mbc.common.manager;

import java.sql.Connection;

import javax.persistence.EntityManager;

import com.mbc.common.dao.DBManager;
import com.mbc.common.dao.DBManagerFactory;

public abstract class AbstractMgr {
	protected String sessionId = "";
	protected DBManager dbManager;
	protected EntityManager entityManager;
	
	protected void openConnection() throws Exception
	{
		if(sessionId.equals(""))
			entityManager = DBManagerFactory.getEmFactory().createEntityManager();
		else
			entityManager = DBManagerFactory.getEntityManager(sessionId);
	}
	
	protected void openJDBCConnection()throws Exception{
		dbManager = DBManagerFactory.getDBManager(sessionId);
	}
	
	protected void closeJDBCConnection()throws Exception{
		dbManager.closeConnection();
	}
	
	protected Connection getConnection(){
		return dbManager.getConnection();
	}
	
	protected void closeConnection(){
		if(entityManager != null && entityManager.isOpen()){
			entityManager.clear();
			entityManager.close();
		}
	}
	
	protected void beginTransaction(){
		if(entityManager != null){
			entityManager.getTransaction().begin();
		}
	}
	
	protected void commitTransaction(){
		if(entityManager != null){
			entityManager.getTransaction().commit();
		}
	}
	
	protected void rollbackTransaction(){
		if(entityManager != null){
			if(entityManager.getTransaction().isActive())
				entityManager.getTransaction().rollback();
		}
	}
}
